package top.ezzz.base;

import top.ezzz.user.IntMap;

import java.util.HashMap;

public class FIbDemo {

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());

        int fib = fib2(20);
        System.out.println("    fib = " + fib);

        System.out.println(System.currentTimeMillis());
    }

    public static int fib3(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }
        int curr = 1;
        int prev = 1;
        for (int i = 3; i <= n; i++) {
            int sum = curr + prev;
            prev = curr;
            curr = sum;
            System.out.println("sum = " + sum);

        }
        return curr;
    }

    public static int fib2(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }
        IntMap fibMap = new IntMap().set(0, 0).set(1, 1).set(2, 1);
        for (int i = 3; i <= n; i++) {
            int sum = fibMap.get(i - 1) + fibMap.get(i - 2);
            fibMap.put(i, sum);
        }
        return fibMap.get(n);
    }

    public static int fib(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }
        int sum = fib(n - 1) + fib(n - 2);
        System.out.println("n = " + n + "\t  sum = " + sum);
        return sum;
    }

    public static int fib1(int n) {
        if (n == 0) {
            return 0;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        return helper(map, n);
    }

    private static int helper(HashMap<Integer, Integer> map, int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        if (map.get(n) != null) {
            return map.get(n);
        }
        int sum = helper(map, n - 1) + helper(map, n - 2);
        System.out.println("n = " + n + "\t  sum = " + sum);
        map.put(n, sum);
        return map.get(n);
    }


}
